package org.karelun.ideaboard.gef.ui.actions;

import org.eclipse.core.runtime.Assert;
import org.eclipse.emf.common.command.CommandStack;
import org.eclipse.emf.edit.domain.EditingDomain;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IWorkbenchPart;
import org.karelun.ideaboard.gef.ui.parts.IGraphicalEditableProvider;

/**
 * @Author: KarelunHuang
 * @Date: Jan 22, 2013
 **/
public abstract class EditAction extends WorkbenchPartAction{

	public EditAction(IWorkbenchPart part) {
		super(part);
	}
	
	public EditAction(IWorkbenchPart part,int style){
		super(part,style);
	}
	
	public EditAction(IEditorPart editor){
		super(editor);
	}
	
	@Override
	protected boolean calculateEnabled() {
		if(!isEditable()){
			return false;
		}
		return canExecutable();
	}

	protected abstract boolean canExecutable();
	

	protected EditingDomain getEditingDomain(){
		if(getWorkbenchPart() instanceof IGraphicalEditableProvider){
			return ((IGraphicalEditableProvider)getWorkbenchPart()).getEditingDomain();
		}
		Object adapter = getWorkbenchPart().getAdapter(EditingDomain.class);
		if(adapter instanceof EditingDomain){
			return (EditingDomain)adapter;
		}
		Assert.isTrue(false);
		return null;
	}
	
	protected boolean isEditable(){
		if(getWorkbenchPart() instanceof IGraphicalEditableProvider){
			return ((IGraphicalEditableProvider)getWorkbenchPart()).isEditable();
		}
		return false;
	}
	
	protected CommandStack getCommandStack() {
		Object adapter = getWorkbenchPart().getAdapter(CommandStack.class);
		if(adapter instanceof CommandStack){
			return (CommandStack) adapter;
		}
		return getEditingDomain().getCommandStack();
	}
}
